import { defineStore } from "pinia";
import * as Cesium from "cesium";
import Dialog from "@/utils/clickopen/dialogneibo";
import NeiboDialog from "@/utils/clickopen/NeiboDialog";
import arrowImg from "@/assets/arrowUp.svg";
import { getNeiBoPouMianData } from "@/api";
import { useScaleStore } from "@/stores/scaleStore";
export const useNeiboStore = defineStore("neibo", {
  state: () => ({
    viewer: null,
    neibodata: [],
    isVisible: false,
    showArrows: false,
    neiboPrimitives: [],
    arrowEntities: [],
    handler: null,
    dialogs: null,
    neiboProfileDialog: null,
    sla: null,
    today: null,
    // 新增的提示框相关状态
    tooltipElement: null,
    tooltipVisible: false,
    currentDeg: null,
    mouseMoveHandler: null,
    // 用于跟踪当前悬停的内波线
    hoveredNeibo: null,
  }),

  actions: {
    setViewer(viewer) {
      this.viewer = viewer;
    },
    setslaData(sla) {
      this.sla = sla;
    },
    setToday(today) {
      this.today = today;
    },
    setIsVisible(isVisible) {
      try {
        this.isVisible = isVisible;
        if (this.isVisible) {
          this.loadNeibo();
        } else {
          this.clearNeibo();
        }
      } catch (error) {
        console.error("设置可见性失败:", error);
        this.isVisible = false;
        this.clearNeibo();
      }
    },

    setShowArrows(show) {
      try {
        this.showArrows = show;
        if (this.isVisible) {
          if (this.showArrows && this.arrowEntities.length === 0) {
            this.loadArrows();
          } else {
            this.updateArrowsVisibility();
          }
        }
      } catch (error) {
        console.error("设置箭头显示失败:", error);
        this.showArrows = false;
        this.clearArrows();
      }
    },

    setNeiboData(neibodata) {
      try {
        if (!neibodata || !Array.isArray(neibodata)) {
          throw new Error("无效的内波数据");
        }
        this.neibodata = neibodata;
      } catch (error) {
        console.error("设置内波数据失败:", error);
        this.neibodata = [];
        this.clearNeibo();
      }
    },

    loadNeibo() {
      try {
        if (!this.neibodata || this.neibodata.length === 0) {
          throw new Error("没有可加载的内波数据");
        }

        this.clearNeibo();
        this.loadNeiboLines();

        if (this.showArrows) {
          this.loadArrows();
        }

        this.setupClickHandler();
        this.setupMouseMoveHandler();
      } catch (error) {
        console.error("加载内波数据失败:", error);
        this.isVisible = false;
        this.clearNeibo();
        throw error;
      }
    },

    loadNeiboLines() {
      try {
        this.neibodata.forEach((wave) => {
          if (!wave.points || wave.points.length < 2) {
            console.warn("无效的内波点数据:", wave);
            return;
          }

          const positions = wave.points.map((point) =>
            Cesium.Cartesian3.fromDegrees(point.lon, point.lat)
          );

          const polylinePrimitive = new Cesium.Primitive({
            geometryInstances: new Cesium.GeometryInstance({
              geometry: new Cesium.PolylineGeometry({
                positions: positions,
                width: 3,
              }),
              id: wave.id,
              attributes: {
                // 添加自定义属性，便于悬停时识别
                waveData: new Cesium.GeometryInstanceAttribute({
                  componentDatatype: Cesium.ComponentDatatype.FLOAT,
                  componentsPerAttribute: 1,
                  normalize: false,
                  value: [wave.deg],
                }),
              },
            }),
            appearance: new Cesium.PolylineMaterialAppearance({
              material: new Cesium.Material({
                fabric: {
                  type: "Color",
                  uniforms: {
                    color: new Cesium.Color(1, 0, 0, 0.7),
                  },
                },
              }),
            }),
          });

          this.viewer.scene.primitives.add(polylinePrimitive);
          this.neiboPrimitives.push({
            primitive: polylinePrimitive,
            data: wave,
          });
        });
      } catch (error) {
        console.error("加载内波线失败:", error);
        this.clearNeiboLines();
        throw error;
      }
    },

    loadArrows() {
      try {
        if (!this.neibodata || this.neibodata.length === 0) {
          throw new Error("没有可加载的内波数据");
        }

        this.clearArrows();

        this.neibodata.forEach((wave) => {
          if (wave.points && wave.points.length > 0 && typeof wave.deg === "number") {
            this.addDirectionArrows(wave);
          } else {
            console.warn("无效的内波方向数据:", wave);
          }
        });
      } catch (error) {
        console.error("加载箭头失败:", error);
        this.clearArrows();
        throw error;
      }
    },

    addDirectionArrows(wave) {
      try {
        const arrowSpacing = 0.15;
        const positions = wave.points;
        const deg = wave.deg;

        let totalLength = 0;
        for (let i = 1; i < positions.length; i++) {
          totalLength += Cesium.Cartesian3.distance(
            Cesium.Cartesian3.fromDegrees(positions[i - 1].lon, positions[i - 1].lat),
            Cesium.Cartesian3.fromDegrees(positions[i].lon, positions[i].lat)
          );
        }

        const numArrows = Math.max(1, Math.floor(totalLength / (arrowSpacing * 111320)));
        const step = positions.length / numArrows;

        for (let i = 0; i < numArrows; i++) {
          const idx = Math.floor(i * step);
          if (idx < positions.length) {
            const arrow = this.createDirectionArrow(
              positions[idx].lon,
              positions[idx].lat,
              deg,
              wave
            );
            this.arrowEntities.push(arrow);
          }
        }
      } catch (error) {
        console.error("添加方向箭头失败:", error);
        throw error;
      }
    },

    createDirectionArrow(lon, lat, deg, waveData) {
      try {
        const heading = Cesium.Math.toRadians(-deg);

        const arrow = this.viewer.entities.add({
          position: Cesium.Cartesian3.fromDegrees(lon, lat),
          name: `方向箭头 ${deg.toFixed(1)}°`,
          billboard: {
            image: arrowImg,
            width: 20,
            height: 20,
            rotation: heading,
            alignedAxis: Cesium.Cartesian3.UNIT_Z,
            verticalOrigin: Cesium.VerticalOrigin.CENTER,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            show: this.showArrows,
            // 添加鼠标交互样式
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
            scaleByDistance: new Cesium.NearFarScalar(1.5e2, 1.0, 1.5e7, 0.5),
          },
          waveData: waveData,
          // 存储角度信息
          deg: deg,
        });

        return arrow;
      } catch (error) {
        console.error("创建方向箭头失败:", error);
        throw error;
      }
    },

    setupMouseMoveHandler() {
      if (!this.viewer) return;

      // 移除旧的事件处理器
      if (this.mouseMoveHandler) {
        this.viewer.screenSpaceEventHandler.removeInputAction(
          Cesium.ScreenSpaceEventType.MOUSE_MOVE
        );
        this.mouseMoveHandler = null;
      }

      // 创建提示框元素
      if (!this.tooltipElement) {
        this.createTooltipElement();
      }

      // 添加新的事件处理器
      this.mouseMoveHandler = this.viewer.screenSpaceEventHandler.setInputAction((movement) => {
        if (!this.isVisible) {
          this.hideTooltip();
          return;
        }

        const scaleStore = useScaleStore();
        const scale = scaleStore.currentScale || 1;

        // 反向计算坐标 - 用于拾取对象
        const adjustedPickPosition = new Cesium.Cartesian2(
          movement.endPosition.x / scale,
          movement.endPosition.y / scale
        );

        // 原始坐标 - 用于显示标签位置
        const originalPosition = new Cesium.Cartesian2(
          movement.endPosition.x,
          movement.endPosition.y
        );

        const pickedObject = this.viewer.scene.pick(adjustedPickPosition);

        // 检查是否悬停在箭头上
        if (pickedObject && pickedObject.id && pickedObject.id.deg !== undefined) {
          this.showTooltip(pickedObject.id.deg, originalPosition);
          this.hoveredNeibo = null;
          return;
        }

        // 检查是否悬停在内波线上
        if (pickedObject && pickedObject.primitive) {
          const foundNeibo = this.neiboPrimitives.find(
            (item) => item.primitive === pickedObject.primitive
          );

          if (foundNeibo) {
            this.hoveredNeibo = foundNeibo;
            this.showTooltip(foundNeibo.data.deg, originalPosition);
            return;
          }
        }

        // 没有悬停在任何相关对象上
        this.hideTooltip();
        this.hoveredNeibo = null;
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    },

    createTooltipElement() {
      this.tooltipElement = document.createElement("div");
      this.tooltipElement.style.position = "absolute";
      this.tooltipElement.style.backgroundColor = "rgba(0, 0, 0, 0.8)";
      this.tooltipElement.style.color = "white";
      this.tooltipElement.style.padding = "5px 10px";
      this.tooltipElement.style.borderRadius = "4px";
      this.tooltipElement.style.pointerEvents = "none";
      this.tooltipElement.style.fontFamily = "Arial, sans-serif";
      this.tooltipElement.style.fontSize = "12px";
      this.tooltipElement.style.zIndex = "9999";
      this.tooltipElement.style.display = "none";
      this.tooltipElement.style.whiteSpace = "nowrap";
      this.tooltipElement.style.boxShadow = "0 2px 5px rgba(0,0,0,0.3)";
      this.tooltipElement.style.transition = "opacity 0.2s";

      document.body.appendChild(this.tooltipElement);
    },

    showTooltip(deg, mousePosition) {
      if (!this.tooltipElement) return;

      this.tooltipElement.innerHTML = `波向: ${deg.toFixed(1)}°`;
      this.tooltipElement.style.left = `${mousePosition.x + 15}px`;
      this.tooltipElement.style.top = `${mousePosition.y + 15}px`;
      this.tooltipElement.style.display = "block";
      this.tooltipElement.style.opacity = "1";
    },

    hideTooltip() {
      if (this.tooltipElement) {
        this.tooltipElement.style.opacity = "0";
        setTimeout(() => {
          if (this.tooltipElement) {
            this.tooltipElement.style.display = "none";
          }
        }, 200);
      }
    },

    async setupClickHandler() {
      try {
        if (this.handler) {
          this.handler.destroy();
          this.handler = null;
        }

        this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.handler.setInputAction(async (click) => {
          try {
            const scaleStore = useScaleStore();
            const scale = scaleStore.currentScale || 1;

            // 反向计算坐标
            const adjustedPosition = new Cesium.Cartesian2(
              click.position.x / scale,
              click.position.y / scale
            );

            const pickedObject = this.viewer.scene.pick(adjustedPosition);
            if (!Cesium.defined(pickedObject)) return;

            let waveData = null;

            // 检查是否点击了箭头
            if (pickedObject.id && pickedObject.id.waveData) {
              waveData = pickedObject.id.waveData;
            }
            // 检查是否点击了内波线
            else if (pickedObject.primitive) {
              const foundPrimitive = this.neiboPrimitives.find(
                (item) => item.primitive === pickedObject.primitive
              );
              if (foundPrimitive) {
                waveData = foundPrimitive.data;
              }
            }

            if (!waveData) return;

            const ray = this.viewer.camera.getPickRay(click.position);
            const cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);

            // 获取剖面数据
            const poumian = await getNeiBoPouMianData({
              ctime: this.today,
              id: waveData.id,
            });

            // 判断sla数据是否存在
            if (this.sla) {
              await this.showNeiboInfo(waveData, cartesian);
            } else {
              console.warn("无SLA数据，不显示海表面高度弹窗");
            }

            // 判断剖面数据是否存在
            if (poumian && poumian.length > 0 && poumian[0].data) {
              this.showNeiboProfile(poumian, waveData, cartesian);
            } else {
              console.warn("无剖面数据，不显示温度断面弹窗");
            }
          } catch (error) {
            console.error("处理点击事件失败:", error);
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      } catch (error) {
        console.error("初始化点击处理器失败:", error);
        this.handler = null;
      }
    },

    showNeiboInfo(waveData, position) {
      try {
        if (this.dialogs) {
          try {
            this.dialogs.windowClose();
            this.dialogs = null;
          } catch (e) {
            console.error("关闭弹窗时出错:", e);
          }
          return new Promise((resolve) => {
            setTimeout(() => {
              this.createNewDialog(waveData, position);
              resolve();
            }, 50);
          });
        } else {
          this.createNewDialog(waveData, position);
        }
      } catch (error) {
        console.error("显示内波信息失败:", error);
      }
    },

    async createNewDialog(waveData, position) {
      try {
        if (!waveData || !position) {
          throw new Error("无效的内波数据或位置");
        }

        if (!this.viewer || !this.viewer.scene) {
          throw new Error("Cesium viewer未初始化");
        }

        requestAnimationFrame(() => {
          this.dialogs = new Dialog({
            viewer: this.viewer,
            position: { _value: position },
            title: "海表面高度",
            gridData: this.sla,
            roadPath: waveData.points,
            additionalInfo: `方向: ${waveData.deg.toFixed(1)}° (正北为0°，顺时针)`,
          });
        });
      } catch (error) {
        console.error("创建弹窗失败:", error);
      }
    },

    showNeiboProfile(profileData, waveData, position) {
      try {
        if (this.neiboProfileDialog) {
          this.neiboProfileDialog.windowClose(true);
          this.neiboProfileDialog = null;
        }

        if (!profileData?.length) {
          console.warn("无剖面数据可显示");
          return;
        }

        requestAnimationFrame(() => {
          try {
            this.neiboProfileDialog = new NeiboDialog({
              viewer: this.viewer,
              position: { _value: position },
              title: "内波温度断面",
              gridData: profileData[0].data,
              roadPath: waveData.points,
              additionalInfo: `深度剖面 (ID: ${waveData.id})`,
            });
          } catch (error) {
            console.error("创建剖面弹窗失败:", error);
          }
        });
      } catch (error) {
        console.error("显示内波剖面失败:", error);
      }
    },

    updateArrowsVisibility() {
      try {
        this.arrowEntities.forEach((entity) => {
          if (entity && entity.billboard) {
            entity.billboard.show = this.showArrows;
          }
        });
      } catch (error) {
        console.error("更新箭头可见性失败:", error);
      }
    },

    clearNeiboLines() {
      try {
        this.neiboPrimitives.forEach((item) => {
          if (item && item.primitive) {
            this.viewer.scene.primitives.remove(item.primitive);
          }
        });
        this.neiboPrimitives = [];
        this.hoveredNeibo = null;
      } catch (error) {
        console.error("清除内波线失败:", error);
        this.neiboPrimitives = [];
      }
    },

    clearArrows() {
      try {
        this.arrowEntities.forEach((entity) => {
          if (entity) {
            this.viewer.entities.remove(entity);
          }
        });
        this.arrowEntities = [];
      } catch (error) {
        console.error("清除箭头失败:", error);
        this.arrowEntities = [];
      }
    },

    clearNeibo() {
      try {
        // 1. 清理图形和箭头
        this.clearNeiboLines();
        this.clearArrows();

        // 2. 清理事件处理器
        if (this.handler) {
          this.handler.destroy();
          this.handler = null;
        }

        if (this.mouseMoveHandler && this.viewer) {
          this.viewer.screenSpaceEventHandler.removeInputAction(
            Cesium.ScreenSpaceEventType.MOUSE_MOVE
          );
          this.mouseMoveHandler = null;
        }

        // 3. 清理提示框
        if (this.tooltipElement && this.tooltipElement.parentNode) {
          this.tooltipElement.parentNode.removeChild(this.tooltipElement);
        }
        this.tooltipElement = null;
        this.tooltipVisible = false;
        this.currentDeg = null;
        this.hoveredNeibo = null;

        // 4. 清理弹窗
        const cleanupTasks = [];
        if (this.dialogs) {
          cleanupTasks.push(
            new Promise((resolve) => {
              this.dialogs.windowClose();
              setTimeout(() => {
                this.dialogs = null;
                resolve();
              }, 100);
            })
          );
        }

        if (this.neiboProfileDialog) {
          cleanupTasks.push(
            new Promise((resolve) => {
              this.neiboProfileDialog.windowClose();
              setTimeout(() => {
                this.neiboProfileDialog = null;
                resolve();
              }, 100);
            })
          );
        }

        return Promise.all(cleanupTasks);
      } catch (error) {
        console.error("清除内波数据失败:", error);
        this.neiboPrimitives = [];
        this.arrowEntities = [];
        this.handler = null;
        this.mouseMoveHandler = null;
        this.dialogs = null;
        this.neiboProfileDialog = null;
        this.tooltipElement = null;
        this.hoveredNeibo = null;
      }
    },

    toggleNeiboVisibility() {
      try {
        this.setIsVisible(!this.isVisible);
      } catch (error) {
        console.error("切换内波可见性失败:", error);
        this.isVisible = false;
        this.clearNeibo();
      }
    },

    toggleArrowsVisibility() {
      try {
        this.setShowArrows(!this.showArrows);
      } catch (error) {
        console.error("切换箭头可见性失败:", error);
        this.showArrows = false;
        this.clearArrows();
      }
    },
  },
});
